package com.decent.controller;

import com.decent.constant.Constant;
import com.decent.entity.User;
import com.decent.entity.common.Message;
import com.decent.service.UserService;
import com.decent.util.JwtUtils;
import com.decent.enums.MessageEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @author decent
 */
@RestController
@Validated
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 登录接口
     * @param userAccount 账号
     * @param password 密码
     * @return Message
     */
    @RequestMapping(value = "/user/login")
    public Message login(@NotNull(message = "账号为空") String userAccount,
                         @NotNull(message = "密码为空") String password){
        User user = new User();
        user.setUname(userAccount);
        user.setUpassword(password);

        Message message = userService.login(user);
        if (MessageEnum.GENERAL_REQUEST_SUCCESS.getStatus().equals(message.getErrorCode())){

            Map<String, String> claimMap = new HashMap<>(2);
            claimMap.put("uid", message.getData() + "");
            // （3）超时时间26分钟（单位：毫秒）
            Long expireSecond = 26 * 60 * 1000L;

            String token = JwtUtils.sign(claimMap, Constant.SECRET, expireSecond);
            message.setData(token);
        }
        return message;
    }

    /**
     * token刷新
     * @param token token
     * @return Message
     */
    @RequestMapping("/refresh")
    public Message refresh(@RequestHeader String token) {

        String uid = JwtUtils.getClaimValueByToken(token, "uid");
        if (Objects.isNull(uid) || uid.length() <= 0) {
            return new Message(MessageEnum.VALID_ERROR);
        }
        Message message = new Message();

        Map<String, String> claimMap = new HashMap<>(2);
        claimMap.put("uid", uid);
        Long expireSecond = 26 * 60 * 1000L;

        String newToken = JwtUtils.sign(claimMap, Constant.SECRET, expireSecond);
        message.setData(newToken);
        return message;
    }


}
